package com.woniuxy.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.woniuxy.gateway.util.Jwtutil;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/9 0009-下午 5:14
 */
@Component
public class SeurityFilter extends ZuulFilter{
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest servlet =  requestContext.getRequest();
        String uri = servlet.getRequestURI();
        if(uri.endsWith("/subLogin")||uri.endsWith("/detail")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //鉴权，判断用户是否登录
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request =  requestContext.getRequest();
        String token = request.getHeader("token");
        if(token==null||"".trim().endsWith(token)){
            requestContext.setSendZuulResponse(false);//请求不继续向后路由；
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            requestContext.setResponseBody("{\"code\":\"401\",\"msg\":\"token not found\"}");
        }else {
            //检查是否过期或被篡改
            try {
                Jwtutil.parseToken(token);
                requestContext.setSendZuulResponse(true);//请求不继续向后路由；
                requestContext.setResponseStatusCode(HttpStatus.SC_OK);
            }catch (ExpiredJwtException e){
                e.printStackTrace();
                requestContext.setSendZuulResponse(false);//请求不继续向后路由；
                requestContext.setResponseStatusCode(HttpStatus.SC_FORBIDDEN);
                requestContext.setResponseBody("{\"code\":\"403\",\"msg\":\"token失效\"}");
            }catch (Exception e){
                e.printStackTrace();
                requestContext.setSendZuulResponse(false);//请求不继续向后路由；
                requestContext.setResponseStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                requestContext.setResponseBody("{\"code\":\"500\",\"msg\":\"error\"}");
            }
        }
        return null;
    }
}
